<template>
  <div class="addUser">
    <el-form :model="form" :rules="rules" ref="ruleForm" label-width="80px">
      <el-form-item label="姓名" prop="user_name">
        <el-input v-model="form.user_name" placeholder="输入业务员姓名"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="tel">
        <el-input v-model="form.tel" placeholder="输入业务员手机号"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit('ruleForm')">{{isEdit ? '编辑' : '添加'}}</el-button>
        <!-- <el-button>取消</el-button> -->
      </el-form-item>
    </el-form>
  </div>
</template>
  
  <script>
import { addBusinessUser, editBusinessUser } from "@/api/business";
import { isValidPhoneNumber } from "@/utils/validate";
export default {
  name: "addUser",
  props: {
    isEdit: {
      default: false,
      type: Boolean
    },
    editForm: {
      default: {},
      type: Object
    }
  },
  data() {
    var validateTel = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入法人手机号"));
      } else {
        if (!isValidPhoneNumber(value)) {
          callback(new Error("手机号格式不正确"));
        } else {
          callback();
        }
      }
    };
    return {
      form: {
        tel: "",
        user_name: ""
      },
      rules: {
        user_name: [
          { required: true, message: "请输入业务员姓名", trigger: "blur" }
        ],
        tel: [{ required: true,validator: validateTel, trigger: "blur" }]
      }
    };
  },
  mounted() {
    this.initial();
  },
  methods: {
    async initial() {
      if (this.isEdit) {
        let { tel, user_name, id } = this.editForm;
        this.form.tel = tel;
        this.form.user_name = user_name;
        this.form.id = id;
      }
    },
    onSubmit(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          if (this.isEdit) {
            let result = await editBusinessUser(this.form);
            if (result.code == 200) {
              this.$message.success(result.msg || "编辑成功");
              setTimeout(() => {
                this.$emit("refresh");
              }, 500);
            }
          } else {
            let result = await addBusinessUser(this.form);
            if (result.code == 200) {
              this.$message.success(result.msg || "添加成功");
              setTimeout(() => {
                this.$emit("refresh");
              }, 500);
            }
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    }
  }
};
</script>
  
<style lang="scss" scoped>
.addUser {
}
</style>
  